package com.fand.manager.handler;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import com.fand.stater.constant.EventCodeEnum;
import com.fand.stater.handler.SysUserESIndexRecordHandler;
import com.fand.stater.model.SysUserDetailDTO;
import com.fand.stater.model.es.SysUserESIndexRecord;
import com.fand.common.util.IPUtil;
import com.fand.common.util.JsonUtils;
import com.fand.common.util.ResultHelp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * @Author: Galen
 * @Date: 2019/3/28-9:17
 * @Description: 认证成功的处理
 **/
@Slf4j
public class SysAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private SysUserESIndexRecordHandler sysUserESIndexRecordHandler;

    public SysAuthenticationSuccessHandler(SysUserESIndexRecordHandler sysUserESIndexRecordHandler) {
        this.sysUserESIndexRecordHandler = sysUserESIndexRecordHandler;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        SysUserDetailDTO sysUserDetailDTO = (SysUserDetailDTO) authentication.getPrincipal();
        log.info("SysAuthenticationSuccessHandler onAuthenticationSuccess() 用户信息为:{}", JsonUtils.objectToJson(sysUserDetailDTO));

        /**
         * 登录成功记录日志
         */
        SysUserESIndexRecord sysUserESIndexRecord = SysUserESIndexRecord.builder()
                .dateTime(DateUtil.formatDateTime(new Date()))
                .time(System.currentTimeMillis())
                .ip(request.getRemoteHost())
                .address(IPUtil.ip2Address(request.getRemoteHost()))
                .UserId(sysUserDetailDTO.getId())
                .userName(sysUserDetailDTO.getRealName())
                .userCode(sysUserDetailDTO.getUsername())
                .eventCode(EventCodeEnum.LOGIN.getCode())
                .build();
        sysUserESIndexRecordHandler.sendRecord(sysUserESIndexRecord);

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonUtils.objectToJson(ResultHelp.success("登录成功")));
        response.getWriter().flush();
        response.getWriter().close();
    }
}
